import TableList from '@/components/TableList';
import { PageContainer } from '@ant-design/pro-components';
import '@umijs/max';
import dayjs from 'dayjs';
import { message, Modal } from "antd";
import FormModal from "@/components/FormModal";
import { useRef, useState } from "react";
import TOButton from "@/components/TableList/TOButton";
import TableOperations from "@/components/TableList/TableOperations";
import { changeSelectValues } from '@/components/TableList/utils';
import { EnableState } from '@/common/Enums';
import PortMappingFormMgr from './components/PortMappingForm';
import { portMappingCreate, portMappingDelete, portMappingList, portMappingUpdate } from './service';
import PortMappingConnectListMgr from './components/PortMappingConnectList';
import { Select } from 'antd';
import { licenseList } from '../license/service';
import { useEffect } from 'react';

const PortMappingMgr = () => {
  const [connectListModalVisible, setConnectListModalVisible] = useState(false);
  const [formModalVisible, setFormModalVisible] = useState(false);
  const [selectRecord, setSelectRecord] = useState(null);
  const tableRef = useRef();
  const formRef = useRef();
  const { confirm } = Modal;

  const [licenseOptions, setLicenseOptions] = useState([]);

  const loadLicense = async () => {
    licenseList({}).then(ret => {
      setLicenseOptions(ret.items ? () => {
        return ret.items.map((item) => {
          return {
            label: item.licenseName,
            value: item.licenseKey
          }
        });
      } : []);
    });
  }
  useEffect(() => {
    loadLicense()
  }, [])
  const columns = [
    {
      title: '序号',
      align: 'center',
      dataIndex: 'index',
      valueType: 'indexBorder',
      width: 50,
    },
    {
      title: 'ID',
      dataIndex: 'id',
      width: 100,
      hideInSearch: true,
      hidden: true
    },
    {
      title: '映射名称',
      dataIndex: 'portMappingName',
      width: 100,
    },
    {
      title: '授权码',
      dataIndex: 'licenseKey',
      width: 100,
      renderFormItem: (_, { defaultValue }) => {
        return <Select
          showSearch
          placeholder='请选择授权码'
          options={licenseOptions}
        />
      }
    },
    {
      title: '监听端口',
      dataIndex: 'sourcePort',
      width: 100,
    },
    {
      title: '目标Ip',
      dataIndex: 'targetIp',
      width: 100,
    },
    {
      title: '目标端口',
      dataIndex: 'targetPort',
      hideInSearch: true,
      width: 100,
    },
    {
      title: '状态',
      dataIndex: 'enableState',
      width: 80,
      valueEnum: {
        ...changeSelectValues(EnableState),
      }
    },
    {
      title: '连接数',
      dataIndex: 'connectNumber',
      hideInSearch: true,
      width: 80,
      render: (_, record) => {

        return <a onClick={() => {
          setSelectRecord(record);
          setConnectListModalVisible(true)
        }
        }>{record.connectNumber}</a>
      }
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 150,
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      align: 'center',
      fixed: 'right',
      width: 100,
      search: false,
      render: (_, record) => {
        const operations = [];

        operations.push(<TOButton
          key='edit'
          type='primary'
          text='修改'
          onClick={() => {
            setSelectRecord(record)
            setFormModalVisible(true)
          }}
        />)
        operations.push(<TOButton
          key='del'
          type='danger'
          text='删除'
          onClick={() => {
            confirm({
              title: '删除映射',
              content: `是否删除“${record.tunnelName}”映射？`,
              async onOk() {
                await portMappingDelete({ id: record.id });
                message.success('删除成功')
                tableRef.current.reload();
              }
            });
          }}
        />)
        return <TableOperations operations={operations} />;
      }
    }
  ];

  const addCallback = () => {
    if (selectRecord) setSelectRecord(null)
    setFormModalVisible(true)
  };

  return (
    <PageContainer>
      <TableList
        tableRef={tableRef}
        columns={columns}
        keyName="id"
        labelWidth={95}
        tableRequest={portMappingList}
        addCallback={addCallback}
        toolBarLeftArea="端口映射列表"
      />
      <FormModal
        title={`${selectRecord ? '修改' : '新增'}端口映射`}
        formRef={formRef}
        initFormValue={selectRecord || { isCheck: true, state: true }}
        visible={formModalVisible}
        onVisibleChange={visible => {
          setFormModalVisible(visible)
          if (!visible && selectRecord) {
            setSelectRecord(null)
          }
        }}
        labelCol={5}
        onConfirm={
          async (values) => {
            let request = selectRecord ? portMappingUpdate : portMappingCreate
            if (selectRecord) values.id = selectRecord.id
            values.enableState = values.enableState ? 1 : 0
            try {
              await request(values)
              message.success('提交成功')
              tableRef.current.reload()
              return true
            } catch (e) {
              return false
            }
          }
        }
      >
        <PortMappingFormMgr
          formRef={formRef}
          record={selectRecord}
        />
      </FormModal>

      {connectListModalVisible && (
        <Modal
          title="连接列表"
          closable={{ 'aria-label': 'Custom Close Button' }}
          open={connectListModalVisible}
          onOk={() => { setConnectListModalVisible(false) }}
          onCancel={() => { setConnectListModalVisible(false) }}
          width={"55vw"}
        >
          <PortMappingConnectListMgr portMappingInfo={selectRecord} />
        </Modal>
      )}
    </PageContainer>
  );
};
export default PortMappingMgr;
